import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.swing.*;
import javax.xml.soap.Text;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Optional;


/**
 * @author wuchenxi
 * @date 2020/11/26 下午6:57
 */
public class Start extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("开始图标生成器");

        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 600, 400);

        MenuBar menuBar = new MenuBar();
        menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
        root.setTop(menuBar);

        Menu createType = new Menu("生成方式");
        menuBar.getMenus().add(createType);

        MenuItem handCreate = new MenuItem("手动生成");
        MenuItem autoCreate = new MenuItem("自动生成");
        createType.getItems().addAll(handCreate, autoCreate);

        this.handCreate(root);

        handCreate.setOnAction(event -> {
            primaryStage.setScene(null);
            this.handCreate(root);
            primaryStage.setScene(scene);
            System.out.println("点击了手动生成");
        });

        autoCreate.setOnAction(event -> {
            primaryStage.setScene(null);
            this.autoCreate(primaryStage, root);
            primaryStage.setScene(scene);
            System.out.println("点击了自动生成");
        });


        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void autoCreate(Stage primaryStage, BorderPane root) {


        TextField appName = new TextField();
        appName.setPrefWidth(370);
        TextField appField = new TextField();
        appField.setPrefWidth(370);
        TextField appIconField = new TextField();
        appIconField.setPrefWidth(370);

        Button chooseApp = new Button("请选择应用文件");
        Button chooseAppIcon = new Button("请选择应用图标文件");

        GridPane gridPane = new GridPane();
        gridPane.setVgap(10);
        gridPane.setHgap(10);
        gridPane.setPadding(new Insets(50, 50, 50, 50));
        gridPane.add(new Label("应用名称"), 0, 0);
        gridPane.add(appName, 1, 0);
        gridPane.add(chooseApp, 0, 1);
        gridPane.add(appField, 1, 1);
        gridPane.add(chooseAppIcon, 0, 2);
        gridPane.add(appIconField, 1, 2);

        chooseApp.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择应用文件");
            File file = fileChooser.showOpenDialog(primaryStage);
            if (file != null) {
                appField.setText(file.getAbsolutePath());
                appName.setText(file.getName().substring(0, file.getName().lastIndexOf(".")));
            }
        });
        chooseAppIcon.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择应用图标文件");
            File file = fileChooser.showOpenDialog(primaryStage);
            if (file != null) {
                appIconField.setText(file.getAbsolutePath());
            }
        });

        Button button = this.startCreate(appName, appField, appIconField);
        gridPane.add(button, 1, 3);
        root.setCenter(gridPane);
    }

    /**
     * 手动生成
     *
     * @param root
     * @return
     */
    private void handCreate(BorderPane root) {


        Label nameLabel = new Label("输入应用名称：");
        TextField nameField = new TextField();
        nameField.setPrefWidth(370);

        Label locationLabel = new Label("输入应用路径：");
        TextField locationField = new TextField();
        locationField.setPrefWidth(370);

        Label iconLabel = new Label("输入应用图标路径：");
        TextField iconField = new TextField();
        iconField.setPrefWidth(370);


        Button button = this.startCreate(nameField, locationField, iconField);

        GridPane grid = new GridPane();
        grid.setVgap(10);
        grid.setHgap(10);
        grid.setPadding(new Insets(50, 50, 50, 50));
        grid.add(nameLabel, 0, 0);
        grid.add(nameField, 1, 0);

        grid.add(locationLabel, 0, 1);
        grid.add(locationField, 1, 1);

        grid.add(iconLabel, 0, 2);
        grid.add(iconField, 1, 2);

        grid.add(button, 1, 3);
        root.setCenter(grid);
    }

    private Button startCreate(TextField nameField, TextField locationField, TextField iconField) {
        Button button = new Button("开始生成");
        button.setOnAction(event -> {
            String appName = nameField.getText();
            String appLocation = locationField.getText();
            String iconLocation = iconField.getText();

            if (this.checkParams(appName, appLocation, iconLocation)) {
                return;
            }

            String text = "[Desktop Entry]\n" +
                    "Encoding=UTF-8\n" +
                    "Name=" + appName + "\n" +
                    "Exec=" + appLocation + " %U\n" +
                    "Icon=" + iconLocation + "\n" +
                    "Terminal=false\n" +
                    "Type=Application\n" +
                    "Categories=Development;\n";

            File file = new File(System.getProperty("user.home") + "/.local/share/applications/" + appName + ".desktop");
            try {
                if (file.exists() && this.checkFileExitsAlert()) {
                    writeFile(text, file);
                } else {
                    boolean newFile = file.createNewFile();
                    if (newFile) {
                        writeFile(text, file);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                this.createErrorAlert();
            }
        });
        return button;
    }

    private void createErrorAlert() {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setContentText("操作失败，请重试！");
        alert.showAndWait();
    }

    private boolean checkParams(String appName, String appLocation, String iconLocation) {
        if (appName == null || appName.trim().length() == 0) {
            showWarnDialog("应用名称不能为空！");
            return true;
        }

        if (appLocation == null || appLocation.trim().length() == 0) {
            showWarnDialog("应用路径不能为空！");
            return true;
        }

        if (!new File(appLocation).exists()) {
            showWarnDialog("应用路径不正确，请检查路径后重新输入！");
            return true;
        }

        if (iconLocation == null || iconLocation.trim().length() == 0) {
            showWarnDialog("应用图标路径不能为空！");
            return true;
        }

        if (!new File(iconLocation).exists()) {
            showWarnDialog("应用图标路径不正确，请检查路径后重新输入！");
            return true;
        }
        return false;
    }

    /**
     * 是否覆盖图标文件
     *
     * @return <ul>
     * <li>true:覆盖</li>
     * <li>false:部分改</li>
     * </ul>
     */
    private boolean checkFileExitsAlert() {
        DialogPane dialogPane = new DialogPane();
        dialogPane.setHeaderText("当前应用图标已存在，是否覆盖？");
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        Dialog<Object> dialog = new Dialog<>();
        dialog.setDialogPane(dialogPane);
        Optional<Object> result = dialog.showAndWait();
        return result.isPresent() && result.get().equals(ButtonType.OK);

    }


    private void showWarnDialog(String contentText) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("警告");
        alert.setHeaderText(null);
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    private void writeFile(String text, File file) throws IOException {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(text);
        out.close();

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText("操作成功！");
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
